﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sisocana.Core.Models;
using Sisocana.Core.Interfaces;
using Sisocana.Core;
using Sisocana.Seguridad;
using System.IO;
using System.Text.RegularExpressions;
using Sisocana.Models;
using System.Text;
using SisocanaBackEnd.Models;



namespace Sisocana.Controllers
{
    public class SiteController : Controller
    {
        private ISiteService _siteService;
        private IUsuarioService _usuarioService;
        private ICSSCatService _cssService;
        private IMasterPageCatService _mpService;
        private IRedSocialAsociadoService _rsService;
        private IVideoAsociadoService _videoService;
        private IImagenAsociadoService _imgAService;
        private IFuenteService _fService;
        private INoticiaAsociadaService _sourceService;
        private IONGDefinidaService _ONGDefinidaService;
        private IONGService _ONGService;
        private IWSBusquedaService _busquedaService;

        public SiteController()
            : this(new WSBusquedaService(),  new NoticiaAsociadoService(), new SiteService(), new UsuarioService(),new CSSCatService(),new MasterPageCatService(),new RedSocialAsociadoService(),new FuenteService(), new VideoAsociadoService(), new ImagenAsociadoService(), new ONGDefinidaService(), new ONGService())
        {
        }

        public SiteController(IWSBusquedaService busquedaService,  INoticiaAsociadaService sourceService, ISiteService siteService, IUsuarioService usuarioService, ICSSCatService cssService, IMasterPageCatService mpService, IRedSocialAsociadoService rsService, IFuenteService fService, IVideoAsociadoService vaService, IImagenAsociadoService imgAService, IONGDefinidaService ONGDefinidaService, IONGService ONGService)
        {
            _siteService = siteService;
            _usuarioService = usuarioService;
            _cssService = cssService;
            _mpService = mpService;
            _rsService = rsService;
            _fService = fService;
            _videoService = vaService;
            _imgAService = imgAService;
            _sourceService = sourceService;
            _ONGDefinidaService = ONGDefinidaService;
            _ONGService = ONGService;
            _busquedaService=busquedaService;
        }

        //
        // GET: /Site/

        public ActionResult Index()
        {
            //listo solo los que puede utilizar el usuario.
            string user = User.Identity.Name;
            if (_usuarioService.IsAdminGeneral(user) )
            {
                return View(_siteService.GetAll());
            }
            else
            {
                return View(_siteService.getAllVUser(user));
            }
        }

        //aca esta el tab menu con ajax
        [SiteAdminAuthorize]
        public ActionResult Conf(int idsitio, int tab)
        {
            SiteModel sit = _siteService.Get(idsitio);
            if (sit != null)
            {
                return View(sit);
            }
            else
            {
                return RedirectToAction("Message", "Error", new { mensaje = "The site not exist" });
            }
 
            
        }

        [SiteAdminAuthorize]       
        public ActionResult PConfigure(int id)
        {
            return View(_siteService.Get(id));
        }

        [HttpPost]
        public ActionResult PConfigure(SiteModel sit, String[] selectedUsers)
        {
            try
            {
                _siteService.saveExistingSite(_usuarioService.IsAdminGeneral(User.Identity.Name), sit, selectedUsers);
                return RedirectToAction("Conf", "Site", new { idsitio = sit.id, tab = 2 });
            }
            catch(Exception e)
            {
                ModelState.AddModelError("", e.Message);
                return View(sit);
            }
        }

        [AdminGralAuthorize]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(SiteModel sit, String[] selectedUsers)
        {
            
            if (_siteService.createSite(sit, selectedUsers) == 0)
                return RedirectToAction("Index", "Site");
            else
                return View();
        }

        public ActionResult showUsers()
        {
            return View(_usuarioService.GetAll(u => u.tipo == "S"));
        }

        public ActionResult showSiteAdmin(int siteId)
        {
            ViewData["isGeneral"] = _usuarioService.IsAdminGeneral(User.Identity.Name);
            return View(_usuarioService.GetSiteAdmins(siteId));
        }

        public ActionResult PConfigSearch(int id)
        {
            ViewData["idSitio"] = id;
            IList<WSBusquedaModel> ws = _busquedaService.GetAll(w => w.idSitio == id);
            return View(ws);
        }


        [Authorize]
        public ActionResult CreateSearch(int id)
        {
            WSBusquedaModel ws = new WSBusquedaModel();
            ws.idSitio = id;
            return View(ws);
        }


        [HttpPost]
        public ActionResult CreateSearch(WSBusquedaModel ws)
        {

            try
            {
                if (_busquedaService.createWSBusqueda(ws) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = ws.idSitio,tab=9 });
                else
                    return View(ws);

            }
            catch (Exception)
            {
                return View(ws);
            }

        }


        public ActionResult editSearch(int id)
        {

            WSBusquedaModel ws = _busquedaService.GetSingle(c => c.id == id);
            return View(ws);
        }


        [HttpPost]
        public ActionResult editSearch(WSBusquedaModel ws)
        {

            try
            {
                if (_busquedaService.updateWSBusqueda(ws) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = ws.idSitio,tab=9 });
                else
                    return View();

            }
            catch (Exception)
            {
                return View();
            }

        }
        public ActionResult DeleteSearch(int id)
        {

            WSBusquedaModel wsbm = _busquedaService.GetSingle(c => c.id == id);
            return View(wsbm);

        }

        [HttpPost]
        public ActionResult DeleteSearch(WSBusquedaModel wsbm)
        {
            try
            {
                int res = _busquedaService.deleteWSBusqueda(wsbm);
                if (res == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = wsbm.idSitio, tab = 9 });
                else
                {
                    return RedirectToAction("MessageID", "Error", new { errorid = res });
                }
            }
            catch
            {
                return RedirectToAction("MessageID", "Error", new { errorid = -110 });
            }
        }



        public ActionResult PConfigSources(int id)
        {
            ViewData["idSitio"] = id;
            IList<NoticiaAsociadaModel> sources = _sourceService.GetAll(c => c.idSitio == id);
            return View(sources);
        }

        


        public ActionResult createSources(int id)
        {
            //llenar el combo con todas las redes sociales disponibles.
            IList<NoticiaModel> sources = _fService.GetAllNoticia();

            IList<String> listac = new List<String>();

            foreach (NoticiaModel source in sources)
            {
                listac.Add(source.nombre);
            }
            SelectList lista = new SelectList(listac);
            ViewData["NoticiaNombre"] = lista;

            NoticiaAsociadaModel sourceAsoc = new NoticiaAsociadaModel();
            sourceAsoc.idSitio = id;

            return View(sourceAsoc);
        }

        [HttpPost]
        public ActionResult createSources(NoticiaAsociadaModel source)
        {

            try
            {
                if (_sourceService.createNoticiaAsociado(source) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = source.idSitio, tab=7 });
                else
                    return View(source);

            }
            catch (Exception)
            {
                return View(source);
            }

        }

        public ActionResult editSource(int id)
        {

            NoticiaAsociadaModel source = _sourceService.GetSingle(c => c.id == id);
            source.tagBusqueda = source.tagBusqueda.Trim();
            return View(source);
        }


        [HttpPost]
        public ActionResult editSource(NoticiaAsociadaModel source)
        {

            try
            {
                if (_sourceService.updateNoticiaAsociado(source) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = source.idSitio,tab=7 });
                else
                    return View();

            }
            catch (Exception)
            {
                ModelState.AddModelError("", "An error ocurred while updating the source.");
                return View();
            }

        }

        public ActionResult DeleteSource(int id)
        {

            NoticiaAsociadaModel nam = _sourceService.GetSingle(c => c.id == id);
            return View(nam);

        }

        [HttpPost]
        public ActionResult DeleteSource(NoticiaAsociadaModel nam)
        {
            try
            {
                int res = _sourceService.deleteNoticiaAsociado(nam);
                if (res == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = nam.idSitio, tab = 7 });
                else
                {
                    return RedirectToAction("MessageID", "Error", new { errorid = res });
                }
            }
            catch
            {
                return RedirectToAction("MessageID", "Error", new { errorid = -110 });
            }
        }

        public ActionResult PconfRS(int id)
        {

            ViewData["idSitio"] = id;
            IList<RedSocialAsociadoModel> rss = _rsService.GetAll(c => c.idSitio == id);
            return View(rss);
        }

        

        public ActionResult createRS(int id)
        {
            //llenar el combo con todas las redes sociales disponibles.
            IList<RedesSocialesModel> rss = _fService.GetAllRedesSociales();

            IList<String> listac = new List<String>();

            foreach (RedesSocialesModel rs in rss)
            {
                listac.Add(rs.nombre);
            }
            SelectList lista = new SelectList(listac);
            ViewData["RedesSocialesName"] = lista;

            //armo el modelo de la asociacion aca para poer enviarle el id del sitio donde va.
            RedSocialAsociadoModel rsN = new RedSocialAsociadoModel();
            rsN.idSitio = id;
            
            return View(rsN);
        }


        [HttpPost]
        public ActionResult createRS(RedSocialAsociadoModel rs)
        {

            try
            {
                if ( _rsService.createRedSocialAsociado(rs) == 0)
                    return RedirectToAction("conf", "Site", new { idsitio = rs.idSitio , tab=3 });
                else
                    return View(rs);

            }
            catch (Exception)
            {
                return View(rs);
            }
           
        }
        
        public ActionResult editRS(int id)
        {

            RedSocialAsociadoModel rs = _rsService.GetSingle(c => c.id == id);
            return View(rs);
        }
        

        [HttpPost]
        public ActionResult editRS(RedSocialAsociadoModel rs)
        {

            try
            {
                if (_rsService.updateRedSocialAsociado(rs) == 0)
                    return RedirectToAction("Conf", "Site", new {idsitio = rs.idSitio ,tab=3 });
                else
                    return View();

            }
            catch (Exception)
            {
                return View();
            }
            
        }


        public ActionResult deleteRS(int id)
        {

            RedSocialAsociadoModel rs = _rsService.GetSingle(c => c.id == id);
            return View(rs);
           
        }

        [HttpPost]
        public ActionResult deleteRS(RedSocialAsociadoModel rs)
        {
            int idSitio = rs.idSitio; 
            try
            {
                int res = _rsService.deleteRedSocialAsociado(rs);
                if (res == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = idSitio, tab = 3 });
                else
                {
                    return RedirectToAction("MessageID", "Error", new { errorid = res });
                }
            }
            catch
            {
                return RedirectToAction("MessageID", "Error", new { errorid = -110 });
            }

        }


        //VideoAsociado

        public ActionResult PcreateVideo(int id)
        {
            //llenar el combo con todas las redes sociales disponibles.
            IList<VideoModel> videos = _fService.GetAllVideo();

            IList<String> listac = new List<String>();

            foreach (VideoModel video in videos)
            {
                listac.Add(video.nombre);
            }

            SelectList lista = new SelectList(listac);
            ViewData["VideoAsociadoName"] = lista;

            IList<String> listasize = new List<String>();
            listasize.Add("4");
            listasize.Add("8");
            SelectList lista2 = new SelectList(listasize);
            ViewData["cantVisualizar"] = lista2;

            IList<String> listatipo = new List<String>();
            listatipo.Add("Small");
            listatipo.Add("Html5");

            SelectList lista3 = new SelectList(listatipo, "Small");
            ViewData["tipo"] = lista3;

            VideoAsociadoModel videoN = _videoService.GetSingle(c => c.idSitio == id);
            //armo el modelo de la asociacion aca para poer enviarle el id del sitio donde va.
            if (videoN == null)
            {
                videoN = new VideoAsociadoModel();
                videoN.idSitio = id;
                videoN.id = 0;
                videoN.tipo = "Small";
            }
            else
            {
                if (videoN.tipo.Trim() != "Small")
                {
                    lista3 = new SelectList(listatipo, "Html5");
                    ViewData["tipo"] = lista3;

                    IList<String> lista4 = new List<String>();
                    lista4.Add("1");
                    lista4.Add("2");
                    lista4.Add("3");
                    lista4.Add("4");
                    lista4.Add("5");
                    lista4.Add("6");
                    lista4.Add("7");
                    lista4.Add("8");
                    lista4.Add("9");
                    lista4.Add("10");
                    lista2 = new SelectList(lista4, videoN.cantVisualizar.ToString());
                    ViewData["cantVisualizar"] = lista2;
                }
                else
                {
                    lista2 = new SelectList(listasize, videoN.cantVisualizar.ToString());
                    ViewData["cantVisualizar"] = lista2;
                }

                lista = new SelectList(listac, videoN.VideoAsociadoName.Trim());
                ViewData["VideoAsociadoName"] = lista;

                videoN.id = videoN.id;
            }

            return View(videoN);
        }

        [HttpPost]
        public ActionResult PcreateVideo(VideoAsociadoModel vi)
        {

            try
            {
                if (_videoService.createUpdateVideoAsociado(vi) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = vi.idSitio ,tab=5});
                else
                    return View(vi);
            }
            catch (Exception)
            {
                return View(vi);
            }

        }



        


        //ImagenAsociado

        public ActionResult PcreateImagen(int id)
        {
            //llenar el combo con todas las redes sociales disponibles.
            IList<ImagenModel> imagenes = _fService.GetAllImagenes();

            IList<String> listac = new List<String>();

            foreach (ImagenModel imagen in imagenes)
            {
                listac.Add(imagen.nombre);
            }

            IList<String> listaG = new List<String>();
            listaG.Add("Gallery");
            listaG.Add("Html5");



            ImagenAsociadoModel imagenN = _imgAService.GetSingle(c => c.idSitio == id);
            //armo el modelo de la asociacion aca para poer enviarle el id del sitio donde va.
            if (imagenN == null)
            {
                imagenN = new ImagenAsociadoModel();
                imagenN.idSitio = id;
                imagenN.width = 380;
                imagenN.heigth = 260;

                SelectList lista = new SelectList(listac);
                ViewData["ImagenAsociadoName"] = lista;

                SelectList lista2 = new SelectList(listaG);
                ViewData["photoGallery"] = lista2;
            }
            else
            {
                SelectList lista = new SelectList(listac, imagenN.ImagenAsociadoName.Trim());
                ViewData["ImagenAsociadoName"] = lista;

                SelectList lista2 = new SelectList(listaG, imagenN.photoGallery.Trim());
                ViewData["photoGallery"] = lista2;
            }
            return View(imagenN);
        }

        [HttpPost]
        public ActionResult PcreateImagen(ImagenAsociadoModel imgAdd)
        {
            try
            {
                if (_imgAService.createUpdateImagenAsociado(imgAdd) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = imgAdd.idSitio,tab=6 });
                else
                    return View(imgAdd);
            }
            catch (Exception)
            {
                return View(imgAdd);
            }
        }


        

        //ONGAsociada

        public ActionResult PconfigONGD(int id)
        {
            ViewData["idSitio"] = id;
            IList<ONGDefinidaModel> ONGs = _ONGDefinidaService.GetAll(c => c.sitioId == id);
            return View(ONGs);
        }

        

        public ActionResult createONGD(int id)
        {

            IList<ONGModel> ongs = _ONGService.GetAll();

            IList<String> listac = new List<String>();

            foreach (ONGModel rs in ongs)
            {
                listac.Add(rs.nombre);
            }
            SelectList lista = new SelectList(listac);
            ViewData["ongName"] = lista;

            //armo el modelo de la asociacion aca para poer enviarle el id del sitio donde va.
            ONGDefinidaModel ong = new ONGDefinidaModel();
            ong.sitioId = id;

            return View(ong);
        }

        [HttpPost]
        public ActionResult createONGD(ONGDefinidaModel ong)
        {
            try
            {
                if (_ONGDefinidaService.createONGDefinida(ong) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = ong.sitioId,tab=8 });
                else
                    return View(ong);
            }
            catch (Exception e)
            {
                return View(ong);
            }
        }

        public ActionResult updateONGD(int id)
        {
            ONGDefinidaModel ongd = _ONGDefinidaService.GetSingle(a => a.id == id);
            ongd.Pais = ongd.Pais.Trim();
            ongd.Ciudad = ongd.Ciudad.Trim();
            ongd.CP = ongd.CP.Trim();
            ongd.Estado = ongd.Estado.Trim();
            ongd.Dir = ongd.Dir.Trim();
            ongd.CoordX = ongd.CoordX.Trim();
            ongd.CoordY = ongd.CoordY.Trim();
            IList<ONGModel> ongs = _ONGService.GetAll();

            IList<String> listac = new List<String>();

            foreach (ONGModel rs in ongs)
            {
                listac.Add(rs.nombre);
            }
            SelectList lista = new SelectList(listac,ongd.ongName);
            ViewData["ongName"] = lista;

            return View(ongd);
        }

        [HttpPost]
        public ActionResult updateONGD(ONGDefinidaModel ong)
        {
            try
            {
                if (_ONGDefinidaService.updateONGDefinida(ong) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = ong.sitioId,tab=8 });
                else
                    return View(ong);
            }
            catch (Exception e)
            {
                return View(ong);
            }

        }

        public ActionResult changeStateONGD(int id)
        {
            ONGDefinidaModel ongd = _ONGDefinidaService.GetSingle(a => a.id == id);
            return View(ongd);
        }

        [HttpPost]
        public ActionResult changeStateONGD(ONGDefinidaModel ong)
        {
            try
            {
                if (_ONGDefinidaService.changeStateONGDefinida(ong.id) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = ong.sitioId,tab=8 });
                else
                    return View(ong);
            }
            catch(Exception e)
            {
                return View(ong);
            }

        }

        public ActionResult PconfVisual(int id)
        {


            SiteModel sit = _siteService.GetSingle(s => s.id == id);
            
            var csscat = _cssService.GetAll();
            var mastercat = _mpService.GetAll();

            List<Recurso> listampr = new List<Recurso>();
            List<Recurso> listacssr = new List<Recurso>();

            foreach (var mp in mastercat)
            {
                Recurso R1 = new Recurso { nombre = mp.nombreMaster.Trim(), desc = mp.descripcion.Trim(), mpAso = "" };
                listampr.Add(R1);
            }

            foreach (var css in csscat)
            {
                Recurso R1 = new Recurso { nombre = css.nombreCSS.Trim(), desc = css.descripcion.Trim(), mpAso = css.MasterPageName.Trim() };
                listacssr.Add(R1);
            }


            //paso el arreglo para el js que va a cargar los combos fuckink MVC no me deja crear eventos de
            // server en las vista , complementos pagos lo hacen , si alguien quiere donar..

            ViewData["masters"] = listampr;
            ViewData["csss"] = listacssr;
            ViewData["mpD"] = sit.name_master.Trim();
            ViewData["cssD"] = sit.name_css.Trim();



            return View(sit);

        }

        [HttpPost]
        public ActionResult PconfVisual([Bind(Exclude = "logo")] SiteModel sit,Boolean wp)
        {
            try
            {

            //obtenemos la variable wp.

            HttpPostedFileBase logo = Request.Files["logo"];

            SiteModel sitio = new SiteModel();
            sitio.id = sit.id;
            sitio.name_css = sit.name_css;
            sitio.name_master = sit.name_master;
              


            if (logo != null & logo.ContentLength > 0)
            {
                sitio.logoNomb = logo.FileName;
                sitio.logoExt = logo.ContentType;

                byte[] img = new byte[logo.InputStream.Length];
                logo.InputStream.Read(img, 0, img.Length);
                sitio.logo= img;
            }


                if (_siteService.saveConfVisual(sitio) == 0)
                {
                    if (wp)
                    {
                        TakeFoto(sitio.id);
                    }
                    return RedirectToAction("Conf", "Site",new{idsitio=sit.id,tab=3});
                }
                else
                {
                    //generar la foto tiro error
                    return RedirectToAction("Message", "Error", new { mensaje = "Imposible to generate the Web preview" });
                   
                }
            }
            catch (Exception)
            {
                return RedirectToAction("Message", "Error", new { mensaje = "Unidentified error" });
            }           
        }

        

        public ActionResult PconfEstado(int id)
        {
            SiteModel sitio = _siteService.GetSingle(a => a.id == id);
            if (sitio == null)
            {
                ModelState.AddModelError("", "The site does exist");
                return View();
            }
            else
            {
                IList<String> listac = new List<String>();
                listac.Add("Maintence");
                listac.Add("On Line");
                listac.Add("Inactive");
                SelectList lista;
                switch (sitio.estado)
                {
                    case "O":
                        lista = new SelectList(listac, "On Line");
                        break;
                    case "M":
                        lista = new SelectList(listac, "Maintence");
                        break;
                    default:
                        lista = new SelectList(listac, "Inactive");
                        break;

                }
                ViewData["estado"] = lista;
                return View(sitio);
            }

        }

        [HttpPost]
        public ActionResult PconfEstado(SiteModel sitio)
        {
            try
            {
                if (_siteService.changeState(sitio.id, sitio.estado) == 0)
                    return RedirectToAction("Conf", "Site", new { idsitio = sitio.id ,tab=10});
                else
                {
                    ModelState.AddModelError("", "The were problems with the state");
                    return View(sitio);
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "The were problems with the state");
                return View(sitio);
            }

        }
        
       

        public void Imagen(int id)
        {            
            SiteModel sit = _siteService.GetSingle(c => c.id == id);
            Response.ContentType = sit.logoExt;
            Response.BinaryWrite(sit.logo);
        }


        public void ImagenT(int id)
        {
            byte[] imageData = null;
            MemoryStream ms = null;
            System.Drawing.Image fullsizeImage = null;
            String imageID = null;

            try
                {
                    SiteModel sit = _siteService.GetSingle(c => c.id == id);                    
                    imageData = sit.logo;                    

                    ms = new MemoryStream(imageData);
                    fullsizeImage = System.Drawing.Image.FromStream(ms);

                    Response.ContentType = "image/Jpeg";
                    ImageResize ir = new ImageResize();

                    // Load your image and perform any resizing here

                    ir.File = fullsizeImage;                    
                    ir.Height = 40;                    
                    ir.Width = 40;
                    //get the thumbnail

                    ir.GetThumbnail().Save(Response.OutputStream,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
                finally
                {
                    ms.Close();
                }
            
        }

        public ActionResult PUploadImages(int id)
        {
            string path = "Content\\images\\Site\\" + id;
            FrontEndServices.SaveFileServiceClient frontEnd = new FrontEndServices.SaveFileServiceClient();
            ViewData["FileEntryCollection"] = frontEnd.getFiles(path);
            return View(id);
        }

        [HttpPost]
        public JsonResult PUploadImages(int? id)
        {
            HttpPostedFileBase file = Request.Files[0];
            if (HasFile(file)) try
                {
                    string realPath = "Content\\images\\Site\\" + id + "\\" + file.FileName;
                
                    FrontEndServices.Streamed.FileTransferServiceClient frontEnd = new FrontEndServices.Streamed.FileTransferServiceClient();
                    if (frontEnd.SaveFile(realPath, file.InputStream))
                        return Json(new { name = file.FileName+" uploaded correctly", type = file.ContentType, size = file.ContentLength });
                }
                catch (Exception e) { 
                
                return Json(new { name = "Error while uploading \n" + e.Message +"   \n " +e.InnerException });
                }
            return Json(new { name = "Error while uploading \n" });
        }

        [HttpPost]
        public JsonResult DeleteImage(int idSitio, string fileName)
        {
            try
            {
                string path = "Content\\images\\Site\\" + idSitio + "\\" + fileName;
                FrontEndServices.SaveFileServiceClient frontEnd = new FrontEndServices.SaveFileServiceClient();
                if(frontEnd.deleteFile(path))
                    return Json(new { message = "File deleted", success = true });            
            }
            catch (Exception) { }
            return Json(new { message = "Error: file couldn't be deleted", success = false });
        }

        public static bool HasFile(HttpPostedFileBase file)
        {
            return file != null && file.ContentLength > 0;
        }

        private bool saveMasterPage(HttpPostedFileBase file, MasterPageModel masterModel)
        {
            if (HasFile(file) && Path.GetExtension(file.FileName).Equals(".master", StringComparison.OrdinalIgnoreCase))
            {
                MasterPageCatModel masterPage = new MasterPageCatModel();
                masterPage.nombreMaster = masterModel.Name;
                masterPage.descripcion = masterModel.Description;
                masterPage.path = @"~/Content/UserMP/" + masterPage.nombreMaster + "/" + masterPage.nombreMaster + Path.GetExtension(file.FileName);
                string realPath = "Content\\UserMP\\" + masterPage.nombreMaster + "\\" + masterPage.nombreMaster + Path.GetExtension(file.FileName);
                
                FrontEndServices.Streamed.FileTransferServiceClient frontEnd = new FrontEndServices.Streamed.FileTransferServiceClient();
                if (frontEnd.SaveFile(realPath, file.InputStream))
                {
                    _mpService.addMasterPage(masterPage);
                    return true;
                }
            }
            return false;
        }

        private bool saveCSS(StylesheetModel css, string masterPageName)
        {
            if (HasFile(css.File) && Path.GetExtension(css.File.FileName).Equals(".css", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    string realPath = "Content\\UserMP\\" + masterPageName + "\\" + css.Name + Path.GetExtension(css.File.FileName);
                
                    FrontEndServices.Streamed.FileTransferServiceClient frontEnd = new FrontEndServices.Streamed.FileTransferServiceClient();
                    if (frontEnd.SaveFile(realPath, css.File.InputStream))
                    {
                        CSSCatModel cssModel = new CSSCatModel()
                        {
                            nombreCSS = css.Name,
                            descripcion = css.Description,
                            path = @"~/Content/UserMP/" + masterPageName + "/" + css.Name + Path.GetExtension(css.File.FileName),
                            MasterPageName = masterPageName
                        };
                            _cssService.createCSSCat(cssModel);
                            return true;
                    }
                }
                catch { }
            }
            return false;
        }

        private bool saveImageOrScript(string folderName, HttpPostedFileBase file, string masterPageName)
        {
            if (HasFile(file) && Path.GetExtension(file.FileName).Equals(".zip", StringComparison.OrdinalIgnoreCase))
            {
                string realPath = "Content\\UserMP\\" + masterPageName + "\\" + folderName + "\\" + Path.GetFileName(file.FileName);

                FrontEndServices.Streamed.FileTransferServiceClient frontEnd = new FrontEndServices.Streamed.FileTransferServiceClient();
                if (frontEnd.SaveFile(realPath, file.InputStream))
                    return true;
            }
            return false;
        }
        
        public ActionResult LoadMasterPageAndCss(int? id)
        {
            return View(new LoadMasterPageAndCssModel(id));
        }

        [HttpPost]
        public ActionResult LoadMasterPageAndCss(LoadMasterPageAndCssModel model)
        {
            if(ModelState.IsValid)
            try
            {
                StringBuilder errorMessage = new StringBuilder();
                if (saveMasterPage(model.MasterPage.File, model.MasterPage))
                {
                    // Saving stylesheets
                    foreach (StylesheetModel stylesheet in model.Stylesheets)
                        if (!saveCSS(stylesheet, model.MasterPage.Name))
                            errorMessage.AppendFormat("Error while uploading stylesheet {0}.\n", stylesheet.Name);

                    // Saving images
                    if(!saveImageOrScript("images", model.Images, model.MasterPage.Name))
                        errorMessage.AppendLine("Error while uploading image package");

                    // Saving scripts
                    if (!saveImageOrScript("scripts", model.Scripts, model.MasterPage.Name))
                        errorMessage.AppendLine("Error while uploading scripts package");

                    if (errorMessage.Length > 0)
                        return View("SiteError", new MessageModel("Load master pages and css", "We are sorry, some errors occured while uploading", errorMessage.ToString()));
                    else if (model.SiteId.HasValue)
                        return RedirectToAction("Conf", "Site", new { idsitio = model.SiteId, tab = 2 });
                    else
                        return RedirectToAction("Index", "Site");
                }
                else
                    return View("SiteError", new MessageModel("Load master pages and css", "We are sorry...", "The master page could not be uploaded"));
            }
            catch (Exception e)
            {
                return View("SiteError", new MessageModel("Load master pages and css", "We are sorry...", e.Message));
            }
            return View(model);
        }

        /*
        [HttpPost]
        public ActionResult LoadMasterPageAndCss(MasterPageCatModel masterModel)
        {
            try
            {
                if(saveMasterPage(Request.Files["MP"], masterModel))
                foreach (string fileKey in Request.Files)
                {
                    Match match = Regex.Match(fileKey, "^.*?(\\d+)$");
                    if (match.Success)
                    {
                        string fileId = match.Groups[1].Value;
                        if (fileKey.StartsWith("css_file"))
                            saveCSS(fileId, Request.Files[fileKey], masterModel);
                        
                    }else if (fileKey == "images")
                        saveImageOrScript("images", Request.Files[fileKey], masterModel);
                    else if (fileKey == "scripts")
                        saveImageOrScript("scripts", Request.Files[fileKey], masterModel);
                }                
                return View();
            }
            catch (Exception e)
            {
                return RedirectToAction("Message", "Error", new { message = e.Message, action = "Load master pages and css" });
            }
        }
        */
        public ActionResult AffectedAreas(int idSitio)
        {
            ViewBag.idSitio = idSitio;
            return View(_siteService.getAreasAfectadas(idSitio));
        }
        
        [HttpPost]
        public ActionResult AffectedAreas(int idSitio, IList<AffectedAreaMarker> areasAfectadas)
        {
            try
            {
                var areasNuevas = areasAfectadas.Where(a => a.Action == "add");
                var areasModificadas = areasAfectadas.Where(a => a.Action == "update");
                var areasEliminadas = areasAfectadas.Where(a => a.Action == "remove");

                _siteService.agregarAreasAfectadas(idSitio, areasNuevas);
                _siteService.actualizarAreasAfectadas(idSitio, areasModificadas);
                _siteService.eliminarAreasAfectadas(idSitio, areasEliminadas);
                return RedirectToAction("Conf", "Site", new { idsitio = idSitio, tab = 1 });
            }
            catch (Exception e)
            {
                return RedirectToAction("Message", "Error", new { message = e.Message, action = "Affected areas"});
            }
        }

        private void TakeFoto(int sitID)
        {
            string _bitmapPath = System.Configuration.ConfigurationManager.AppSettings["UrlPreviews"] + sitID.ToString() + ".jpg";
            string servPath = Server.MapPath(_bitmapPath);
            WebsiteThumbnail.generarImagen(sitID,servPath);

        }

       
        /*Generador de las tabs para generar las tabs.*/


        public ActionResult getAjaxTab(int id,int idSitio)
        {
            string viewName = string.Empty;

            switch (id)
            {
                case 1:
                    viewName = "PConfigure";
                    break;
                case 2:
                    viewName = "PconfVisual";
                    break;
                case 3:
                    viewName = "PconfRs";
                    break;
                case 4:
                    viewName = "PcreateVideo";
                    break;
                case 5:
                    viewName = "PcreateImagen";
                    break;
                case 6:
                    viewName = "PUploadImages";
                    break;
                case 7:
                    viewName = "PConfigSources";
                    break;
                case 8:
                    viewName = "PconfigONGD";
                    break;
                case 9:
                    viewName = "PConfigSearch";
                    break;
                case 10:
                    viewName = "PconfEstado";
                    break;
            }

            System.Threading.Thread.Sleep(200);
            //return PartialView(viewName, sit);
            return RedirectToAction(viewName, "Site", new { id = idSitio });
        }


        public ActionResult _taberror(int id){
            return View();
        }
    }

    public class Recurso
    {
        public string nombre { get; set; }
        public string desc { get; set; }
        public string mpAso { get; set; }
    }
}
